#include "IAnimation.h"
IAnimation::IAnimation(Vector2 renderSize, Vector2 offset) : IVisible(nullptr, renderSize, offset)
{
}
void IAnimation::addFrame(Image *frame, real intervaltime)
{
    frames_list.push_back(frame);
    intervaltime_list.push_back(intervaltime);
}

void IAnimation::update(real delta)
{
    if (isPaused)
    {
        return;
    }
    if (timer.getElapsedDoubleSeconds() >= intervaltime_list.at(index))
    {
        index++;
        if (index >= frames_list.size())
        {
            loopCount--;
            if (loopCount == 0)
            {
                isPaused = true;
            }
            else if (this->loopCount < 0)
            {
                start();
            }
            else
            {
                start(loopCount);
            }
        }
        else
        {
            timer.recordTimePoint();
            setImage(frames_list[index]);
        }
    }
}

void IAnimation::start(int index, int loopCount)
{
    if (frames_list.empty())
    {
        return;
    }
    timer.recordTimePoint();
    this->index = so_min(index, frames_list.size() - 1);
    setImage(frames_list[this->index]);
    if (loopCount > 0)
    {
        this->loopCount = loopCount;
    }
    else
    {
        this->loopCount = -1;
    }
}

void IAnimation::pause(bool val)
{
    isPaused = val;
}

bool IAnimation::paused()
{
    return isPaused;
}

void IAnimation::setAnchor(Anchor val)
{
    anchor = val;
}

Anchor IAnimation::getAnchor()
{
    return anchor;
}
